import router from '@/router'
import store from '@/store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

const writeList = ['/login', '/404']
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const token = store.getters.token
  if (token) {
    const userInfo = store.getters.userInfo
    if (!userInfo.username) {
      await store.dispatch('user/getUserInfo')
    }
    if (to.path === '/login') {
      next('/')
      NProgress.done()
      Message({
        message: '您已经登录过了，别调皮',
        type: 'info'
      })
    } else {
      next()
    }
  } else {
    if (writeList.indexOf(to.path) != -1) {
      next()
    } else {
      next(`/login?_redirect=${to.path}`)
      Message({
        message: '您没有登录，请重新登录',
        type: 'info'
      })
    }
  }
})

router.afterEach((to, from) => {
  NProgress.done()
})
